package com.huajx.tuopuda.client.udp.handler;

import com.huajx.core.Hboot;
import com.huajx.core.kit.HttpKit;
import com.huajx.tuopuda.client.udp.TuopudaDirect;
import com.huajx.tuopuda.client.udp.TuopudaException;
import com.huajx.tuopuda.client.udp.TuopudaMessage;
import com.huajx.tuopuda.client.udp.codec.setting.SearchNetMachineCodec;
import com.huajx.tuopuda.client.udp.config.SchoolConfig;
import com.huajx.tuopuda.client.udp.model.Drive;
import com.huajx.util.ByteUtil;
import com.huajx.util.HexUtil;
import com.huajx.util.NetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @program: di-parent
 * @description:
 * @author: lisa 叶新华
 * @create: 2019-10-08 10:35
 */
public class SearchNetMachineHandler extends AbstractTuopudaHandler {
    private static final Logger logger = LoggerFactory.getLogger(SearchNetMachineHandler.class);
    private final static  String POST_URL = SERVER_URL + "/di/tuopuda/machine/";
    private static SearchNetMachineHandler me;
    private static SchoolConfig config;
    public static SearchNetMachineHandler me() {
    	config = Hboot.config(SchoolConfig.class);
        if (me == null) {
            me = new SearchNetMachineHandler();
        }
        return me;
    }

    @Override
    public void send(String ip, int port, int sn) {
        byte[] bytes = SearchNetMachineCodec.getInstance(sn).encode();
        
        try {
            byte[] bytes1 = sendAndReceive(ip, port, bytes);
            //decode(bytes1);
        } catch (TuopudaException e) {
            e.printStackTrace();
        }
    }

    private void decode(byte[] bytes) {
    	String schoolId = config.getId();
    	String schoolName = config.getName();
    	 if (bytes.length != 34) {
         }
    	 Drive drive = new Drive();
         int direct = ByteUtil.bytesToShort(new byte[]{bytes[3], bytes[4]});
         switch (direct) {
             case TuopudaDirect.D_1101:
            	 int address = ByteUtil.bytesToInt(new byte[]{bytes[1], bytes[2]});
            	 String mask = getMsk(Arrays.copyOfRange(bytes, 15, 19));
            	 String ip = getIp(Arrays.copyOfRange(bytes, 11, 15));
            	 String gateway = gateWay(Arrays.copyOfRange(bytes, 19, 23));
            	 String mac = getMac(Arrays.copyOfRange(bytes, 5, 11));
            	 drive.setSn(address);
            	 drive.setGateway(gateway);
            	 drive.setMac(mac);
            	 drive.setMask(mask);
            	 drive.setIp(ip);
            	 drive.setSchoolId(schoolId);
            	 String json="{\"schoolName\":\""+schoolName+"\",\"schoolId\":\""+schoolId+"\", \"sn\":\""+address+"\",\"ip\":\""+ip+"\",\"gateway\":\""+gateway+"\""
            	 		+ " ,\"mac\":\""+mac+"\",\"mask\":\""+mask+"\"}";
            	 try {
                     HttpKit.post(POST_URL + schoolId, json);
                 } catch (Exception e) {
                     logger.error("向平台端传输数据个,失败,平台端链接信息错误！");
                 }
            	 break;
             default:
            	  break;
         }

    }

    private void localNetworkInfo() {
        InetAddress ip = null;
        NetworkInterface ni = null;
        try {
            ip = InetAddress.getLocalHost();
            ni = NetworkInterface.getByInetAddress(ip);// 搜索绑定了指定IP地址的网络接口
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<InterfaceAddress> list = ni.getInterfaceAddresses();// 获取此网络接口的全部或部分

        for (InterfaceAddress ia : list) {
            String ipStr = ia.getAddress().getHostAddress();
//            logger.info(ipStr);
            logger.info("IP:{}--MASK:{}",ipStr, getMask(ia));
        }

        // InterfaceAddresses
        // 所组成的列表
//        if (list.size() > 0) {
//            int mask = list.get(0).getNetworkPrefixLength(); // 子网掩码的二进制1的个数
//            byte[] bytes = ByteUtil.bytesByLength(mask, 4);
//            logger.info("Mask: {}-- ", HexUtil.bytesToHex(bytes));
//            StringBuilder maskStr = new StringBuilder();
//            int[] maskIp = new int[4];
//            for (int i = 0; i < maskIp.length; i++) {
//                maskIp[i] = (mask >= 8) ? 255 : (mask > 0 ? (mask & 0xff) : 0);
//                mask -= 8;
//                maskStr.append(maskIp[i]);
//                if (i < maskIp.length - 1) {
//                    maskStr.append(".");
//                }
//            }
//            System.out.println("SubnetMask:" + maskStr);
//        }
    }
    private String getMask(InterfaceAddress ia) {
        int mask = ia.getNetworkPrefixLength();
        StringBuilder maskStr = new StringBuilder();
        int[] maskIp = new int[4];
        for (int i = 0; i < maskIp.length; i++) {
            maskIp[i] = (mask >= 8) ? 255 : (mask > 0 ? (mask & 0xff) : 0);
            mask -= 8;
            maskStr.append(maskIp[i]);
            if (i < maskIp.length - 1) {
                maskStr.append(".");
            }
        }
//        logger.info("Mask: {}-- ", maskStr);
        return maskStr.toString();
    }
    /**
     * 获取msk 地址
     * @param bytes
     * @return
     */
    public static String getMsk(byte[] bytes){
    	 int msk1 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[0]}),16);
    	 int msk2 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[1]}),16);
    	 int msk3 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[2]}),16);
    	 int msk4 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[3]}),16);
    	 String msk=msk1+"."+msk2+"."+msk3+"."+msk4;
    	 return msk;
    }
    
    /**
     * 获取ip 地址
     * @param bytes
     * @return
     */
    public static String getIp(byte[] bytes){
    	 int ip1 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[0]}),16);
    	 int ip2 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[1]}),16);
    	 int ip3 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[2]}),16);
    	 int ip4 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[3]}),16);
    	 String ip=ip1+"."+ip2+"."+ip3+"."+ip4;
    	 return ip;
    }
    /**
     * 获取gateWay 网关地址
     * @param bytes
     * @return
     */
    public static String gateWay(byte[] bytes){
    	 int gateWay1 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[0]}),16);
    	 int gateWay2 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[1]}),16);
    	 int gateWay3 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[2]}),16);
    	 int gateWay4 = Integer.parseInt( HexUtil.bytesToHex(new byte[]{bytes[3]}),16);
    	 String gateWay=gateWay1+"."+gateWay2+"."+gateWay3+"."+gateWay4;
    	 return gateWay;
    }
    /**
     * 获取gateWay 网关地址
     * @param bytes
     * @return
     */
    public static String getMac(byte[] bytes){
    	 String mac1=HexUtil.bytesToHex(new byte[]{bytes[0]});
    	 String mac2=HexUtil.bytesToHex(new byte[]{bytes[1]});
    	 String mac3=HexUtil.bytesToHex(new byte[]{bytes[2]});
    	 String mac4=HexUtil.bytesToHex(new byte[]{bytes[3]});
    	 String mac5=HexUtil.bytesToHex(new byte[]{bytes[4]});
    	 String mac6=HexUtil.bytesToHex(new byte[]{bytes[5]});
    	 String mac=mac1+"-"+mac2+"-"+mac3+"-"+mac4+"-"+mac5+"-"+mac6;
    	 return mac;
    }
}
